import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
  Query,
} from '@nestjs/common';
import { PermissionService } from './permission.service';
import { CreatePermissionDto } from './dto/create-permission.dto';
import { UpdatePermissionDto } from './dto/update-permission.dto';
import { RequireLogin, RequirePermission } from 'src/custom.decorator';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
  ApiQuery,
  ApiParam,
} from '@nestjs/swagger';

@ApiTags('权限管理')
@ApiBearerAuth()
@Controller('permission')
@RequireLogin()
export class PermissionController {
  constructor(private readonly permissionService: PermissionService) {}

  @Post()
  @RequirePermission('permission:create')
  @ApiOperation({ summary: '创建权限' })
  @ApiResponse({ status: 201, description: '创建成功' })
  @ApiResponse({ status: 400, description: '权限编码已存在' })
  async create(@Body() createPermissionDto: CreatePermissionDto) {
    return await this.permissionService.create(createPermissionDto);
  }

  @Get('list')
  @RequirePermission('permission:query')
  @ApiOperation({ summary: '获取权限列表' })
  @ApiQuery({
    name: 'pageNum',
    description: '页码',
    required: false,
    type: Number,
  })
  @ApiQuery({
    name: 'pageSize',
    description: '每页数量',
    required: false,
    type: Number,
  })
  @ApiQuery({ name: 'code', description: '权限编码', required: false })
  @ApiQuery({ name: 'description', description: '权限描述', required: false })
  async findAll(
    @Query('pageNum') pageNum = 1,
    @Query('pageSize') pageSize = 10,
    @Query('code') code?: string,
    @Query('description') description?: string,
  ) {
    return await this.permissionService.findAll(
      pageNum,
      pageSize,
      code,
      description,
    );
  }

  @Get(':id')
  @RequirePermission('permission:query')
  @ApiOperation({ summary: '获取权限详情' })
  @ApiParam({ name: 'id', description: '权限ID' })
  async findOne(@Param('id') id: string) {
    return await this.permissionService.findOne(+id);
  }

  @Put(':id')
  @RequirePermission('permission:update')
  @ApiOperation({ summary: '更新权限' })
  @ApiParam({ name: 'id', description: '权限ID' })
  @ApiResponse({ status: 200, description: '更新成功' })
  @ApiResponse({ status: 400, description: '权限不存在/权限编码已存在' })
  async update(
    @Param('id') id: string,
    @Body() updatePermissionDto: UpdatePermissionDto,
  ) {
    return await this.permissionService.update(+id, updatePermissionDto);
  }

  @Delete(':id')
  @RequirePermission('permission:delete')
  @ApiOperation({ summary: '删除权限' })
  @ApiParam({ name: 'id', description: '权限ID' })
  @ApiResponse({ status: 200, description: '删除成功' })
  @ApiResponse({
    status: 400,
    description: '权限不存在/该权限已被角色使用，无法删除',
  })
  async remove(@Param('id') id: string) {
    return await this.permissionService.remove(+id);
  }
}
